<template>
  <div class="app-container">
    <!-- 页面工具栏 -->
    <PageTools>
      <span slot="left">共{{ pageTotal }}条记录</span>
      <template v-slot:right>
        <el-button type="primary" size="small" @click="addClick" v-permission="'aa'">新增员工</el-button>
        <el-button type="primary" size="small" @click="$router.push('/employees/import')">从excel导入</el-button>
        <el-button type="primary" size="small" @click="exportExcel">导出到excel</el-button>
      </template>
    </PageTools>
    <br>
    <el-card>
      <!-- 员工列表 -->
      <el-table :data="tableData" :border="true" v-loading="loading">
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column prop="username" label="姓名" align="center" sortable />
        <el-table-column prop="staffPhoto" label="头像" align="center">
          <template v-slot="{ row }">
            <!-- 当 :src="row.staffPhoto" 加载失败，会自动加载<img> 作为默认显示图片-->
            <el-avatar :size="50" :src="row.staffPhoto" @click.native="showQrCode(row.staffPhoto)"><img src="@/assets/common/bigUserHeader.png" alt=""></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" align="center" sortable />
        <el-table-column prop="workNumber" label="工号" align="center" sortable />
        <el-table-column prop="formOfEmployment" label="聘用形式" align="center" :formatter="formatEmploy" sortable />
        <el-table-column prop="departmentName" label="部门" align="center" sortable />
        <el-table-column prop="timeOfEntry" label="入职日期" align="center" sortable>
          <template v-slot="{ row }">
            <!-- 使用过滤器将时间格式化 -->
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="账户状态" align="center" sortable>
          <template v-slot="{ row }">
            <el-switch :value="row.enableState == 1" disabled />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="280">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small" @click="">转正</el-button>
            <el-button type="text" size="small" @click="">调岗</el-button>
            <el-button type="text" size="small" @click="">离职</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delClick(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination layout="prev, pager, next" :page-size="page.size" :total="pageTotal" @current-change="changePage" />
    </el-card>
    <!-- 新增员工弹层 -->
    <AddEmployee :title="title" :dialogVisible.sync="dialogVisible" @confirmClick="confirmClick"></AddEmployee>
    <!-- 二维码弹层 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog" class="qrDialog">
        <canvas ref="myCanvas" />
    </el-dialog>
    <!-- 角色弹层 -->
    <AssignRole ref="assignRole" :showRoleDialog.sync="showRoleDialog" :userId="userId"></AssignRole>
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import employeesEnum from '@/utils/enum/employees'
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/utils/filters'
import QrCode from 'qrcode'
export default {
  name: 'EmployeesIndex',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      loading: false, // 表格加载状态
      tableData: [], // 表格数据
      page: {
        page: 1, // 当前页码
        size: 10 // 每页条数
      },
      pageTotal: 0, // 总条数
      title: '新增员工', // 新增或编辑弹层的标题
      dialogVisible: false, // 控制新增或编辑弹层的显示
      showCodeDialog: false, // 控制二维码弹层的显示
      showRoleDialog: false, // 控制角色弹层的显示
      userId: '', // 传给角色弹层的id
    }
  },
  methods: {
    // 获取员工列表
    async getEmployeesList() {
      this.loading = true
      const data = await getEmployeesList(this.page)
      this.loading = false
      this.tableData = data.rows
      this.pageTotal = data.total
    },
    // 切换页码
    changePage(currentPage) {
      this.page.page = currentPage
      this.getEmployeesList()
    },
    // 格式化聘用形式
    formatEmploy(row, column, cellValue, index) {
      // find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
      const res = employeesEnum.hireType.find((item) => item.id === cellValue)
      return res ? res.value : '未知'
    },
    // 显示二维码操作
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true 
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 删除操作
    delClick(id) {
      this.$confirm('确定要删除该员工吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        await delEmployee(id)
        this.getEmployeesList()
        this.$message.success('删除员工成功')
      }).catch(() => {})
    },
    // 新增操作
    addClick() {
      this.title = '新增员工'
      this.dialogVisible = true
    },
    // 新增或编辑成功
    confirmClick() {
      this.getEmployeesList()
      this.dialogVisible = false
    },
    // 编辑角色操作
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getEmployeeBasicInfo(id)
      this.showRoleDialog = true
    },
    // 导出到excel
    async exportExcel() {
      // 设置中/英文对应关系
      const userRelation = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const { rows } = await getEmployeesList({page: 1, size: this.pageTotal})
      // 下面将[{}, {}]形式转为[[],[]]形式
      const data = []
      rows.forEach(item => {
        const user = []
        Object.values(userRelation).forEach(val => {
          if(val === 'timeOfEntry' || val === 'correctionTime') {
            // 需额外对日期型数据进行格式处理
            user.push(formatDate(item[val], 'yyyy/MM/dd'))
          } else if(val === 'formOfEmployment'){
            // 需额外对聘用形式进行格式处理
            const res = employeesEnum.hireType.find((obj) => obj.id == item[val])
            const type = res ? res.value : '未知'
            user.push(type)
          } else {
            // 其它不用处理，直接push
            user.push(item[val])
          }
        })
        data.push(user)
      })
      // 由于xlsx插件体积比较大，导出功能也不是一个常用功能，所以这里建议使用懒加载方式
      import ('@/utils/vendor/ExportExcel').then(excel => {
        // excel是引入文件的导出对象
        excel.export_json_to_excel({
          header: Object.keys(userRelation),
          data: data, // data 需为[[],[]]二维数组格式
          filename: '员工详细表',
          // multiHeader: multiHeader,
          // merges: merges
        })
      })
    }
  },
  created() {
    this.getEmployeesList()
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }
  .qrDialog {
    ::v-deep .el-dialog {
      text-align: center;
      width: 500px;
    }
  }
}
</style>